<template>
    <el-row :gutter="12">
        <el-col :span="6">
            <el-card shadow="hover">
                <template #header>
                    <div class="card-header">
                        <el-icon>
                            <Avatar />
                        </el-icon>
                        <span>个人信息</span>
                    </div>
                </template>
                <div class="avatar-wrapper">
                    <n-avatar :size="120"
                        :src="!avatarVal ? 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg' : avatarVal"
                        round />
                    <div class="shade" @click="centerDialogVisible = true">
                        <el-icon>
                            <Plus style="color: #fff;" />
                        </el-icon>
                    </div>
                </div>
                <div v-for="(item, i) in userinfo" :key="i">
                    <el-divider style="margin: 14px 0;" />
                    <div class="item">
                        <el-icon>
                            <component :is="item.icon" />
                        </el-icon>
                        <span>
                            {{ item.text }}
                        </span>
                        <div style="flex-grow: 1;" />
                        <span>
                            {{ item.data }}
                        </span>
                    </div>
                </div>
            </el-card>
            <el-dialog v-model="centerDialogVisible" title="修改头像" width="50%" align-center>
                <div class="upload">
                    <el-upload class="avatar-uploader"
                        action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <upload-filled />
                        </el-icon>
                    </el-upload>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button type="primary" @click="centerDialogVisible = false">
                            确 认
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </el-col>
        <el-col :span="18">
            <el-card shadow="hover">
                <template #header>
                    <div class="card-header">
                        <el-icon>
                            <Document />
                        </el-icon>
                        <span>基本资料</span>
                    </div>
                </template>
                <el-tabs v-model="activeName" class="demo-tabs">
                    <el-tab-pane label="基本资料" name="first">
                        <el-form :model="form" ref="updateRuleFormRef" :rules="updateRules" label-width="70"
                            status-icon>
                            <el-form-item label="昵称" prop="nickname">
                                <el-input v-model="form.nickname" placeholder="仅支持中英日韩文,12字以内" clearable />
                            </el-form-item>
                            <el-form-item label="邮箱" prop="email">
                                <el-input v-model="form.email" clearable />
                            </el-form-item>
                            <el-form-item label="性别" prop="gender">
                                <el-radio-group v-model="form.gender">
                                    <el-radio :label="0">男</el-radio>
                                    <el-radio :label="1">女</el-radio>
                                    <el-radio :label="2">秘密</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="submitUpdate(updateRuleFormRef)" text>修 改</el-button>
                                <el-button @click="cancel(updateRuleFormRef)" text>取 消</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="修改密码" name="second">
                        <el-form :model="form" ref="resetRuleFormRef" :rules="resetRules" label-width="80">
                            <el-form-item label="旧密码" prop="oldPwd">
                                <el-input v-model="form.oldPwd" show-password clearable required />
                            </el-form-item>
                            <el-form-item label="新密码" prop="newPwd">
                                <el-input v-model="form.newPwd" placeholder="12-18位，英文大小写" show-password clearable
                                    required />
                            </el-form-item>
                            <el-form-item label="二次确认" prop="regNewPwd">
                                <el-input v-model="form.regNewPwd" show-password clearable required />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="submitReset(resetRuleFormRef)" text>修 改</el-button>
                                <el-button @click="cancel(resetRuleFormRef)" text>取 消</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </el-card>
        </el-col>
    </el-row>
</template>

<script setup>
import { computed, reactive, ref } from 'vue';
import { ElMessage, ElButton, ElForm, ElFormItem, ElTabs, ElTabPane, ElCard, ElIcon, ElRadioGroup, ElRadio, ElInput, ElUpload, ElDialog, ElDivider, ElRow, ElCol } from 'element-plus';
import { Document, UploadFilled, Avatar, Plus } from '@element-plus/icons-vue'
import { NAvatar } from 'naive-ui'
import { nicknameRule, passwordRule, emailRule, codeRule } from '@/utils/validate';
import MyStore from '@/stores/modules/MyStore';
import { Update, Reset } from '@/Apis/modules/my';

// 数据渲染
const store = MyStore();
const info = computed(() => store.info);
const updateRuleFormRef = ref();
const resetRuleFormRef = ref();
const registerVal = ref(null);
const nicknameVal = ref(null);
const usernameVal = ref(null);
const genderVal = ref(null);
const emailVal = ref(null);
const rolesVal = ref(null);
const avatarVal = ref(null);
const ageVal = ref(null);

watchEffect(() => {
    if (info.value) {
        const { register, nickname, username, gender, email, roles, avatar, age } = info.value;
        registerVal.value = register;
        nicknameVal.value = nickname;
        usernameVal.value = username;
        genderVal.value = gender;
        emailVal.value = email;
        rolesVal.value = roles === 'SuperAdmin' ? '超级管理员' : '管理员';
        avatarVal.value = avatar;
        ageVal.value = age;
    }
});

const centerDialogVisible = ref(false);
const activeName = ref('first');
const userinfo = computed(() =>
    [
        { text: '昵称', icon: 'EditPen', data: nicknameVal.value },
        { text: '用户名', icon: 'User', data: usernameVal.value },
        { text: '身份', icon: 'Postcard', data: rolesVal.value },
        { text: '邮箱', icon: 'Message', data: emailVal.value },
        {
            text: '性别',
            icon: genderVal.value === 0 ? 'Male' :
                genderVal.value === 1 ? 'Female' : 'Sugar',
            data: genderVal.value === 0 ? '男' :
                genderVal.value === 1 ? '女' : '秘密'
        },
        { text: '年龄', icon: 'Timer', data: ageVal.value },
        { text: '创建日期', icon: 'Calendar', data: registerVal.value }
    ]
);

// 切换头像
const imageUrl = ref('');
const handleAvatarSuccess = (response, uploadFile) => {
    imageUrl.value = URL.createObjectURL()
}
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' || 'image/png' || 'image/jpg') {
        ElMessage.error('头像格式不正确!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像大小不得超过2MB!')
        return false
    }
    return true
}

// 标签页
const form = reactive({
    avatar: avatarVal,
    nickname: nicknameVal,
    email: emailVal,
    gender: genderVal,
    oldPwd: '',
    newPwd: '',
    regNewPwd: ''
});

// 验证两个密码是否一致
const regNewPwdRule = async (rule, value, callback) => {
    if (!value) {
        callback(new Error('密码不能为空！'))
    } else if (value !== form.newPwd) {
        callback(new Error('两次输入的密码不一致!'));
    } else {
        callback();
    }
};

const updateRules = ref({
    nickname: [{ required: true, validator: nicknameRule, trigger: 'blur' }],
    email: [{ required: true, validator: emailRule, trigger: 'blur' }],
})

// 正则验证
const resetRules = ref({
    oldPwd: [{ required: true, validator: passwordRule, trigger: 'blur' }],
    newPwd: [{ required: true, validator: passwordRule, trigger: 'blur' }],
    regNewPwd: [{ required: true, validator: regNewPwdRule, trigger: 'blur' }],
});

const submitUpdate = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const { nickname, email, gender } = form;

            const data = {
                nickname,
                email,
                gender
            };

            await Update(data);
        } else {
            ElMessage.error('验证未通过!');
        }
    })
};

const submitReset = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const { oldPwd, newPwd } = form;

            const data = {
                oldPwd,
                newPwd
            };

            await Reset(data);
        } else {
            ElMessage.error('验证未通过!');
        }
    })
};

// 重置表单
const cancel = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
};
</script>

<style scoped>
.card-header {
    display: flex;
    align-items: center;
}

.item {
    display: flex;
    align-items: center;
}

.avatar-wrapper {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    display: flex;
    margin: 0 auto;
    position: relative;
}

.shade {
    display: none;
    align-items: center;
    justify-content: center;
    position: absolute;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background-color: rgba(51, 51, 51, 0.7);
}

.avatar-wrapper:hover .shade {
    z-index: 10;
    display: flex;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.upload {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
</style>

<style>
.avatar-uploader .el-upload {
    width: 300px;
    height: 300px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    background-color: rgba(221, 209, 221, 0.3);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 60px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>